package com.hf.www.base.intercepter;

import java.util.Arrays;

import com.hf.www.tools.SysConstants;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;

public class LoginInterceptor implements Interceptor {

	private static final Logger LOG = Logger.getLogger(LoginInterceptor.class);

	@Override
	public void intercept(Invocation ai) {
		
		LOG.info(" -- "+ ai.getController().getRequest().getLocalAddr() + "    " +ai.getControllerKey() +"   " +ai.getActionKey());
		LOG.info(" -- session : " + ai.getController().getSession().getAttribute(SysConstants.SESSION_USER));
		Controller controller = ai.getController();
		if (arraySerarch(SysConstants.ACTION_LIMIT_URL,ai.getActionKey())<0 && (arraySerarch(SysConstants.CONTROLLER_UNLIMIT_URL, ai.getControllerKey()) >= 0 || arraySerarch(SysConstants.ACTION_UNLIMIT_URL, ai.getActionKey()) >= 0 )) {
			ai.invoke();
		} else {
			if (null != controller.getSession().getAttribute(SysConstants.SESSION_USER)) {
				ai.invoke();
			} else {
				controller.redirect("/");
			}
		}
	}
	
	public static int arraySerarch(Object[] arrs, Object obj){
		for (int i = 0; i < arrs.length; i++) {
			if(obj != null && obj.equals( arrs[i])){
				return i;
			}
		}
		return -1;
	}
	
	
	public static void main(String[] args) {
		
		String [] arr = new String[]{"/","/example","/login","/check"};
		String str = "/example";
		Arrays.sort(arr);
		long bt = System.currentTimeMillis();
		System.out.println();
		for (int i = 0; i < 100000; i++) {
			if(Arrays.binarySearch(arr,str) >= 0){
				
			}
		}
		
		System.out.println((System.currentTimeMillis() - bt )+ "ms");
		
		bt = System.currentTimeMillis();
		System.out.println();
		for (int i = 0; i < 100000; i++) {
			if(arraySerarch(arr,str) >= 0){
				
			}
		}
		
		System.out.println((System.currentTimeMillis() - bt )+ "ms");
	}

}
